<template>
  <div class="sys-ellipsis">
    <el-tooltip ref="tooltip"
                v-bind="tooltipProps">
      <div class="sys-ellipsis__tooltip--content"
           slot="content"
           v-if="subContent"
           v-html="subContent">
      </div>
    </el-tooltip>
    <div ref="content"
         class="sys-ellipsis__content"
         :style="`-webkit-line-clamp: ${lines}`"
         @mouseenter="handleMouseEnter"
         @mouseleave="handleMouseLeave">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import ElTooltip from 'element-ui/lib/tooltip'
import {debounce} from '@/utils/util'

export default {
  props: {
    ...ElTooltip.props,
    lines: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      tooltipContent: '',
      subContent: ''
    }
  },
  computed: {
    tooltipProps() {
      const props = {...this.$props}
      delete props.lines
      // 如果没有设置位置，默认设为top
      if (!props.placement) props.placement = 'top'
      return props
    }
  },
  methods: {
    handleMouseEnter() {
      if(!this.subContent) {
        if (!this.tooltipProps.content) {
          if (this.$slots.default[0].tag) {
            this.subContent = this.tooltipContent
          } else {
            this.subContent = this.$slots.default[0].text
          }
        }
      }

      const content = this.$refs.content
      const range = document.createRange()
      range.setStart(content, 0)
      range.setEnd(content, content.childNodes.length)
      const rangeHeight = range.getBoundingClientRect().height;

      if (rangeHeight > content.offsetHeight || content.scrollHeight > content.offsetHeight) {
        const tooltip = this.$refs.tooltip
        tooltip.referenceElm = content
        tooltip.$refs.popper && (tooltip.$refs.popper.style.display = 'none');
        tooltip.doDestroy()
        tooltip.setExpectedState(true)
        this.activateTooltip(tooltip)
      }
    },
    handleMouseLeave() {
      const tooltip = this.$refs.tooltip
      if (tooltip) {
        tooltip.setExpectedState(false)
        tooltip.handleClosePopper()
      }
    },
    getContent() {
      const elm = this.$slots.default[0].elm
      return elm.wholeText
    }
  },
  updated() {
    this.tooltipContent = this.getContent()
  },
  mounted() {
    this.tooltipContent = this.getContent()
    this.activateTooltip = debounce(tooltip => tooltip.handleShowPopper(), 50, false, this);
  }
}
</script>

<style lang="scss" scoped>
.sys-ellipsis {
  &__content {
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
}
</style>
